package com.antg;

/**
 * @author Antg
 * @date 2021/10/19  12:56
 */
public class Code_2 {
    public static void main(String[] args) {

    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode();
        ListNode pointer_result = result;
        int carry = 0;//进位值

        while (true){
            /**
             * 思路:从左往右加,和大于10就进位
             * */
            //结束条件,两者遍历完就结束
            if(l1==null&&l2==null&&carry==0){
                break;
            }
            if(l1==null&&l2==null&&carry==1){
                pointer_result.val=1;
                break;
            }


            if(l1==null){
                //如果l1为空
                int tmp = l2.val+carry;
                if(tmp==10){
                    pointer_result.val = 0;
                    carry=1;
                }else{
                    pointer_result.val=tmp;
                    carry=0;
                }
            }else if (l2==null){
                //如果l2为空
                int tmp = l1.val+carry;
                if(tmp==10){
                    pointer_result.val = 0;
                    carry=1;
                }else{
                    pointer_result.val=tmp;
                    carry=0;
                }
            }else{
                int tmp = l1.val+ l2.val+carry;
                if(tmp>=10){
                    pointer_result.val = tmp%10;
                    carry=1;
                }else{
                    pointer_result.val=tmp;
                    carry=0;
                }

            }
            if(l1!=null){
                l1 = l1.next;
            }
            if(l2!=null){
                l2 = l2.next;
            }
            //结束条件,两者遍历完就结束
            if(l1==null&&l2==null&&carry==0){
                break;
            }
            //开辟一个新的节点
            pointer_result.next = new ListNode();
            //移动指针
            pointer_result = pointer_result.next;

        }
        return result;
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}


